import { Alert, EditModal } from '@ycx/ui';
import { useTheme } from '@/store/settingsStore.ts';
import { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from 'react';
import { App, Form, Input } from 'antd';
import { useMutation } from '@tanstack/react-query';
import { useUserId, useUserInfo } from '@/store/userStore.ts';
import AccountServices from '@/api/services/accountServices.ts';
import { useRouter } from '@/router/hooks';
import { md5 } from 'js-md5';
import { validatePasswordStrength } from '@/utils/validatePasswordStrength.ts';
import PwdStrength from '@/pages/personal/PwdStrength.tsx';
import { DefaultPwd } from '#/enmu.ts';

export type ChangePwdModalRef = {
  open: () => void;
};

type FormInstance = {
  oldPassword: string;
  newPassword: string;
  pwdAgain: string;
};

const ChangePasswordModal = forwardRef<ChangePwdModalRef>((_props, ref) => {
  const { message } = App.useApp();
  const theme = useTheme();
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm<FormInstance>();
  const userId = useUserId();
  const router = useRouter();
  const [newPwd, setNewPwd] = useState('');
  const { resetPassword } = useUserInfo();

  const { mutate, isPending } = useMutation({
    mutationFn: AccountServices.update,
    onSuccess: async () => {
      close();
      await message.success('修改密码成功,即将跳转到登录界面');
      router.push('/login');
    },
    onError: (error) => {
      message.error(error.message);
    },
  });

  const handleSubmit = async () => {
    await form.validateFields();
    const data = form.getFieldsValue();
    mutate({
      id: userId!,
      oldPassword: resetPassword ? md5(DefaultPwd.Gov) : md5(data.oldPassword),
      password: md5(data.newPassword),
    });
  };

  const close = () => {
    if (resetPassword) {
      return;
    }
    setOpen(false);
    form.resetFields();
    setNewPwd('');
  };

  const pwdStrength = useMemo(() => {
    return validatePasswordStrength(newPwd);
  }, [newPwd]);

  useImperativeHandle(ref, () => ({
    open: () => {
      setOpen(true);
    },
  }));

  useEffect(() => {
    if (resetPassword) setOpen(true);
  }, [resetPassword]);

  return (
    <EditModal
      theme={theme}
      title="修改密码"
      open={open}
      onClose={close}
      onCancel={close}
      forceRender
      confirmLoading={isPending}
      onOk={handleSubmit}
      maskClosable={false}
      modalRender={(dom) => (
        <Form form={form} layout="vertical">
          {dom}
        </Form>
      )}
    >
      {!resetPassword ? (
        <Form.Item
          label="旧密码"
          name="oldPassword"
          rules={[{ required: true, message: '请输入旧密码' }]}
        >
          <Input.Password />
        </Form.Item>
      ) : (
        <Alert
          theme={theme}
          type="info"
          message="首次登录需要重置密码"
          closable={false}
          className="mb-4"
        />
      )}

      <Form.Item
        label="新密码"
        name="newPassword"
        dependencies={['oldPassword']}
        rules={[
          { required: true, message: '请输入新密码' },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (getFieldValue('oldPassword') === value) {
                return Promise.reject('新密码不能和旧密码相同');
              } else {
                return Promise.resolve();
              }
            },
          }),
        ]}
      >
        <Input.Password onChange={(e) => setNewPwd(e.target.value)} />
      </Form.Item>
      <PwdStrength score={pwdStrength} />
      <Form.Item
        dependencies={['newPassword']}
        label="确认新密码"
        name="pwdAgain"
        required
        rules={[
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value) return Promise.reject('请确认新密码');
              if (getFieldValue('newPassword') === value) {
                return Promise.resolve();
              } else {
                return Promise.reject('两次密码输入不一致');
              }
            },
          }),
        ]}
      >
        <Input.Password />
      </Form.Item>
    </EditModal>
  );
});

export default ChangePasswordModal;
